package com.uobgroup.ews.uam.core.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.uobgroup.ews.uam.core.domain.AccessControl;

@Repository
public class AccessControlDaoImpl extends AbstractJpaDao<AccessControl> implements AccessControlDao {

   public AccessControlDaoImpl() {
      setClazz(AccessControl.class);
   }

   public long count() {
      return entityManager.createQuery("SELECT COUNT(o) FROM AccessControl o", Long.class).getSingleResult();
   }

   public List<AccessControl> findAll(int firstResult, int maxResults) {
      return entityManager.createQuery("SELECT o FROM AccessControl o", AccessControl.class)
            .setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
   }

   @SuppressWarnings("unchecked")
   public List<AccessControl> findByLikeName(String name) {
      Query query = entityManager.createNamedQuery(AccessControl.FINDBYLIKENAME);
      query.setParameter(AccessControl.PARA_NAME, name.toLowerCase() + "%");
      List<AccessControl> accessControls = query.getResultList();
      return accessControls;
   }

   @SuppressWarnings("unchecked")
   public List<AccessControl> findByIds(List<Long> ids) {
      Query query = entityManager.createNamedQuery(AccessControl.FINDBYIDs);
      query.setParameter(AccessControl.PARA_IDs, ids);
      List<AccessControl> accessControls = new ArrayList<AccessControl>();
      if (ids != null || (!ids.isEmpty())) {
         accessControls = query.getResultList();
      }
      return accessControls;
   }

   /*
    * Phuong Tran
    */
   public List<AccessControl> findACLbyType(int type) {
      return entityManager.createQuery("FROM AccessControl acl WHERE acl.type =" + type, AccessControl.class)
            .getResultList();
   }

   /*
    * Phuong Tran
    */
   @Override
   public List<String> findAllACLName() {
      return entityManager.createQuery("SELECT acl.name FROM AccessControl acl", String.class).getResultList();
   }
   
   @Override
   public boolean checkTheAssociationWithRoleSubType(Long Id){
      boolean rtValue = false;
      Query query = entityManager.createNativeQuery("SELECT * FROM ROLESUBTYPEACCESSCONTROL "
            + "WHERE ROLESUBTYPEACCESSCONTROL.AccessControl=" + Id);
      if (query != null) {
         if (query.getResultList().size() > 0) {
            rtValue = true;
         }
      }
      return rtValue;
   }

}
